package com.sos.util;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import com.sos.model.entity.User;
import com.sos.repository.UserRepository;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 用户上下文工具类：封装获取当前登录用户信息的逻辑
 */
@Component
public class UserContextUtils {

    @Resource
    private UserRepository userRepository;

    /**
     * 获取当前登录用户的ID（未登录则抛异常）
     */
    public Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        // 判断是否未登录（匿名用户或无认证信息）
        if (authentication == null
                || authentication.getName() == null
                || authentication instanceof AnonymousAuthenticationToken) {
            throw new CustomException(ErrorCode.NOT_LOGIN);
        }

        // 根据用户名查询用户ID
        String username = authentication.getName();
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

        return user.getId();
    }

}